#include"ram.h"
#include"base.h"
#include<string.h>
#include<stdio.h>


void dev_init(struct device **devices){
    for(int i = 0; i < 256; i++){
        devices[i] = NULL;
    }
}

void dev_register(struct device **devices,struct device *dev){
    if(devices[dev->id] != NULL){
        printf("device %d already registered", dev->id);
        return;
    }
    devices[dev->id] = dev;
}

uint8_t dev_read_b(struct device **devices,uint32_t addr){
    uint8_t data;
    if(devices[addr >> 24] == NULL){
        printf("ID为 %d 的设备无效", addr >> 24);
        return -1;
    }
    if(devices[addr >> 24]->read_b == NULL){
        printf("ID为 %d 的设备不支持字节访问", addr >> 24);
        return -1;
    }
    devices[addr >> 24]->read_b(addr, &data);
    return data;
}

uint16_t dev_read_h(struct device **devices,uint32_t addr){
    uint16_t data;
    if(devices[addr >> 24] == NULL){
        printf("ID为 %d 的设备无效", addr >> 24);
        return -1;
    }
    if(devices[addr >> 24]->read_h == NULL){
        printf("ID为 %d 的设备不支持半字访问", addr >> 24);
        return -1;
    }
    devices[addr >> 24]->read_h(addr, &data);
    return data;
}

uint32_t dev_read_w(struct device **devices,uint32_t addr){
    uint32_t data;
    if(devices[addr >> 24] == NULL){
        printf("ID为 %d 的设备无效", addr >> 24);
        return -1;
    }
    if(devices[addr >> 24]->read_w == NULL){
        printf("ID为 %d 的设备不支持字访问", addr >> 24);
        return -1;
    }
    devices[addr >> 24]->read_w(addr, &data);
    return data;
}

void dev_write_b(struct device **devices,uint32_t addr, uint8_t data){
    if(devices[addr >> 24] == NULL){
        printf("ID为 %d 的设备无效", addr >> 24);
        return;
    }
    if(devices[addr >> 24]->write_b == NULL){
        printf("ID为 %d 的设备不支持字节访问", addr >> 24);
        return;
    }
    devices[addr >> 24]->write_b(addr, data);
}

void dev_write_h(struct device **devices,uint32_t addr, uint16_t data){
    if(devices[addr >> 24] == NULL){
        printf("ID为 %d 的设备无效", addr >> 24);
        return;
    }
    if(devices[addr >> 24]->write_h == NULL){
        printf("ID为 %d 的设备不支持半字访问", addr >> 24);
        return;
    }
    devices[addr >> 24]->write_h(addr, data);
}

void dev_write_w(struct device **devices,uint32_t addr, uint32_t data){
    if(devices[addr >> 24] == NULL){
        printf("ID为 %d 的设备无效", addr >> 24);
        return;
    }
    if(devices[addr >> 24]->write_w == NULL){
        printf("ID为 %d 的设备不支持字访问", addr >> 24);
        return;
    }
    devices[addr >> 24]->write_w(addr, data);
}

